<?php

namespace app\admin\controller;

use aop\AlipayConfig;
use aop\AopCertClient;
use aop\request\AlipayFundTransUniTransferRequest;
use aop\AopClient;
use aop\request\AlipayTradeWapPayRequest;
use app\common\controller\Backend;
use app\common\model\Log;
use think\exception\ValidateException;
use think\facade\Db;

/**
 * 商家提现管理
 *
 * @icon fa fa-circle-o
 */
class Cash extends Backend
{
    protected $relationSearch = true;
    /**
     * Cash模型对象
     * @var \app\common\model\Cash
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Cash;

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看.
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            [$where, $sort, $order, $offset, $limit] = $this->buildparams();
            $builder = $this->model->withJoin(['merchant'])
                ->where($where)
                ->where('cash.is_delete', 1);
            if($this->group_id == 2 && $this->merchant){
                $builder->where('cash.merchant_id', $this->merchant['id']);
            }
            $total = $builder
                ->order($sort, $order)
                ->count();
            $list  = $builder
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
//            dump($list->toArray());die;
            $result = ['total' => $total, 'rows' => $list];

            return json($result);
        }

        return $this->view->fetch();
    }

    /**
     * 详情
     */
    public function detail($ids = null)
    {
        $row = $this->model
            ->with(['merchants'])
            ->field('out_trade_no,merchant_id,amount,handle_fee,cash_amount,status,createtime,truename,alipay_account,pay_time,pay_number,pay_money')
            ->find($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $row = $row->toArray();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if($row){
            $row['status'] = $row['status_text'];
            $row['createtime'] = $row['createtime_text'];
            if($row['status'] != 2){
                $row['pay_time'] = $row['pay_time_text'];
            }else{
                unset($row['pay_time'],$row['pay_number'],$row['pay_money']);
            }

            unset($row['status_text'],$row['createtime_text'],$row['merchant_id'],$row['pay_time_text']);
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 批量审核
     */
    public function examine()
    {
        $ids = $this->request->param('ids');
        $type = $this->request->param('type');
        $this->modelValidate = true;
        if (!$ids) {
            $this->error(__('No Results were found'));
        }
        $row = $this->model->where('id', 'in', $ids)->select();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $is_check = true;
        foreach ($row as $value){
            if($value['status'] != 1){
                $is_check = false;break;
            }
        }
        if(!$is_check){
            $this->error('有非待审核状态的订单');
        }
        Db::startTrans();
        try {
            $merchant_model = new \app\common\model\Merchant();
            $balance_model = new \app\common\model\BalanceLog();
            $platform_log_model = new \app\common\model\PlatformLog();
            $update = ['status' => $type, 'examine_time' => time()];
            foreach ($row as $key=>$value){
                if($type == 2){//通过
                    //支付宝打款
                    $merchant = $merchant_model->where('id', $value['merchant_id'])->find();
                    $res = $this->alipay($value, $merchant);
                    dump($res);die;
                    if(!empty($res->code) && $res->code==10000){
                        $update['pay_number'] = $res->order_id;
                        $update['pay_time'] = strtotime($res->trans_date);
                        $update['pay_time'] = time();
                        $update['pay_money'] = $value['amount'];
                        $platform_log = [
                            'user_id' => $value['merchant_id'],
                            'amount' => $value['amount'],
                            'type' => 2,
                            'log_note' => '商家余额提现',
                            'order_id' => $value['id'],
                            'order_type' => 2,
                            'createtime' => time(),
                        ];
                        $this->model->where('id', $value['id'])->update($update);
                        $platform_log_model->save($platform_log);
                    }else{
                        Db::rollback();
                        $this->error('提现失败');
                    }
                }else{//拒绝
                    $this->model->where('id', $value['id'])->update($update);
                    //返还余额 写入余额流水
                    $merchant_model->where('id', $value['merchant_id'])->Inc('shop_balance', $value['amount'])->update();
                    $balance_model->save(['merchant_id' => $value['merchant_id'], 'amount' => $value['amount'], 'type' => 3, 'log_note' => '商家余额提现审核拒绝返还', 'createtime' => time(), 'order_id' => $value['id'], 'order_type' => 2]);
                }
            }
            Db::commit();
        } catch (ValidateException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (\PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($res){
            $this->success('审核成功！');
        }else{
            $this->error(('审核失败！'));
        }
    }

    /**
     * 支付宝打款
     * @param $order
     * @param $merchant
     * @return mixed
     */
    public function alipay($order, $merchant){
        $root_path = root_path();
        $alipay_config = config("config_alipay.alipay");//正式
//        $alipay_config = config("config_alipay.alipay_test");//沙箱

        $alipayConfig = new AlipayConfig();
        $alipayConfig->setPrivateKey($alipay_config['privateKey']);
        $alipayConfig->setServerUrl($alipay_config['server_url']);
        $alipayConfig->setAppId($alipay_config['app_id']);
        $alipayConfig->setCharset($alipay_config['charset']);
        $alipayConfig->setSignType($alipay_config['sign_type']);
//        $alipayConfig->setEncryptKey("");
        $alipayConfig->setFormat($alipay_config['format']);
        $alipayConfig->setAppCertPath($root_path.$alipay_config['app_public_cert_path']);
        $alipayConfig->setAlipayPublicCertPath($root_path.$alipay_config['alipay_public_cert_path']);
        $alipayConfig->setRootCertPath($root_path.$alipay_config['alipay_root_cert_path']);

        $alipayClient = new AopCertClient($alipayConfig);
        //是否校验自动下载的支付宝公钥证书，如果开启校验要保证支付宝根证书在有效期内
        $alipayClient->isCheckAlipayPublicCert = true;
        $request = new AlipayFundTransUniTransferRequest();
        //业务请求参数
        $bizcontent = json_encode(['out_biz_no'=>$order['out_trade_no'] ,'trans_amount'=>$order['cash_amount'],'product_code'=>'TRANS_ACCOUNT_NO_PWD','biz_scene'=>'DIRECT_TRANSFER','order_title'=>'支付宝提现' , 'payee_info' => ['identity' => $merchant['alipay_account'], 'identity_type' => 'ALIPAY_LOGON_ID', 'name' => $merchant['alipay_name']]], JSON_UNESCAPED_UNICODE);
//        $bizcontent = json_encode(['out_biz_no'=>$order['out_trade_no'] ,'trans_amount'=>$order['amount'],'product_code'=>'TRANS_ACCOUNT_NO_PWD','biz_scene'=>'DIRECT_TRANSFER','order_title'=>'支付宝提现' , 'payee_info' => ['identity' => 'vsytcu7408@sandbox.com', 'identity_type' => 'ALIPAY_LOGON_ID', 'name' => '沙箱环境']]);
        $request->setBizContent($bizcontent);
        $responseResult = $alipayClient->execute($request);
        $responseApiName = str_replace(".","_",$request->getApiMethodName())."_response";
        $response = $responseResult->$responseApiName;
        return $response;
    }

//    public function alipayToPay($order, $merchant){
//        $root_path = root_path();
//        $alipay_config = config("config_alipay.alipay");//正式
//
//        $alipayConfig = new AlipayConfig();
//        $alipayConfig->setPrivateKey($alipay_config['privateKey']);
//        $alipayConfig->setServerUrl($alipay_config['server_url']);
//        $alipayConfig->setAppId($alipay_config['app_id']);
//        $alipayConfig->setCharset($alipay_config['charset']);
//        $alipayConfig->setSignType($alipay_config['sign_type']);
////        $alipayConfig->setEncryptKey("");
//        $alipayConfig->setFormat($alipay_config['format']);
//        $alipayConfig->setAppCertPath($root_path.$alipay_config['app_public_cert_path']);
//        $alipayConfig->setAlipayPublicCertPath($root_path.$alipay_config['alipay_public_cert_path']);
//
//        $alipayClient = new AopCertClient($alipayConfig);
//        $request = new AlipayTradeWapPayRequest();
//        //业务请求参数
//        $bizcontent =json_encode(['body'=>'购买商品' ,'subject'=>'九灵珠宝','out_trade_no'=>$order_number,'total_amount'=>$allmoney,'product_code'=>'QUICK_WAP_WAY' , 'passback_params' => '购买']);
//        $request->setBizContent($bizcontent);
//        $request->setBizContent($bizcontent);
//        $request->setNotifyUrl($notify_url);//异步回调接口
//        $responseResult = $alipayClient->pageExecute($request);
//    }


    /**
     * 删除
     */
    public function del($ids = "")
    {
        $row                 = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->model->where('id', 'in', $ids)->update(['is_delete' => 2, 'deletetime' => time()]);
        $this->success();
    }
}
